package com.simple.datax.transform.tcs;

import org.apache.xmlbeans.XmlObject;

import cn.gov.chinaport.tcs.flow.TcsFlow201Document;
import cn.gov.chinaport.tcs.flow.TcsFlow201ResponseDocument;

import com.simple.datax.api.TransformerException;
import com.simple.datax.xml.ec.EC101MessageDocument;
import com.simple.datax.xml.ec.EC101MessageDocument.EC101Message;
import com.simple.datax.xml.ec.XMLDATA;
import com.simple.datax.xml.tcs.TCS101MessageDocument;
import com.simple.datax.xml.tcs.TCS101MessageDocument.TCS101Message;

/**
 * @Title: Tcs2EcMessageTransformer.java
 * @Package com.simple.datax.transform.tcs
 * @Description: 处理Tcs101Message到Ec101Messasge的转换
 * @author Paladin Chen
 * @date 2013-1-9 下午3:36:18
 * @version V1.0
 */
public class Tcs2EcMessageTransformer extends AbstractTcs2EcTransformer{

	public EC101MessageDocument transform(TCS101MessageDocument xmlDoc) throws TransformerException {
		TCS101Message tcsmsg = ((TCS101MessageDocument) xmlDoc).getTCS101Message();
		com.simple.datax.xml.tcs.MessageHeadDocument.MessageHead tcsMessageHead = tcsmsg.getMessageHead();

		EC101MessageDocument ecmessageDoc = EC101MessageDocument.Factory.newInstance();
		EC101Message ecmessage = ecmessageDoc.addNewEC101Message();
		com.simple.datax.xml.ec.MessageHeadDocument.MessageHead ecMessageHead = ecmessage.addNewMessageHead();

		messageHeadTransform(tcsMessageHead, ecMessageHead);

		try {
			XmlObject tcsBody = XmlObject.Factory.parse(tcsmsg.getMessageBody().xmlText());
			if (tcsBody instanceof TcsFlow201Document) {
				Tcs2EcFlowTransformer t2etransformer = new Tcs2EcFlowTransformer();

				ecmessage.setMessageBody(XMLDATA.Factory.parse(t2etransformer.transform((TcsFlow201Document) tcsBody)
						.toString()));
			} else if (tcsBody instanceof TcsFlow201ResponseDocument) {
				Tcs2EcFlowResponseTransformer t2etransformer = new Tcs2EcFlowResponseTransformer();

				ecmessage.setMessageBody(XMLDATA.Factory.parse(t2etransformer.transform(
						(TcsFlow201ResponseDocument) tcsBody).toString()));
			} else {
				throw new TransformerException("The MsgSubType (TCS 2 EC) is NOT Need NOW, Calling wrong function.");
			}
		} catch (Exception e) {
			throw new TransformerException("Error occur when transform ec xml body.", e);
		}

		return ecmessageDoc;
	}

}
